/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009
    Head of the EIP Laboratory.

*/
package com.spice.im;

import android.app.Activity;




import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

//import com.stb.isharemessage.R;
//import com.stb.isharemessage.ui.list.NearByActivity;
//import com.beem.push.utils.Constants;
import com.beem.push.utils.Constants;
import com.example.android.bitmapfun.util.ObjectCache;
//import com.stb.isharemessage.BeemApplication;
//import com.stb.isharemessage.service.XmppConnectionAdapter;
//import com.stb.isharemessage.ui.wizard.AccConfActivity;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.utils.BeemConnectivity;

/**
 * This class is the main Activity for the Beem project.
 * @author Da Risk <darisk@beem-project.com>
 */
public class Login extends Activity {

    private static final int LOGIN_REQUEST_CODE = 1;
//    private TextView mTextView;
    private String mTextViewStr = "";
    private boolean mIsResult;
    private BeemApplication mBeemApplication;
    private SpiceApplication mSpiceApplication;
    private int isConfig = 0;//0 false 1 true
    private Intent intent = null;
    /**
     * Constructor.
     */
    public Login() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
//	TerminalConfigMgr.setSpecificServer(this,true);//20140704 added by allen just for serverinfo setup
	Intent intent = getIntent(); 
    //0 false 1 true
	isConfig = intent.getIntExtra("isConfig", (int) 0); 
    
	/**Application的生命周期:当所有的Activity都关闭之后，MyApplication的生命周期也结束了*/
	Application spiceapp = getApplication();
	if (spiceapp instanceof SpiceApplication) {
		mSpiceApplication = (SpiceApplication) spiceapp;
	}
	BeemApplication app = BeemApplication.getInstance();
	Log.e("※※※※※※20131206※※※※※※", "※※※※※※※mBeemApplication.is not null="+app);
	if (app instanceof BeemApplication) {
	    mBeemApplication = (BeemApplication) app;
	    Log.e("※※※※※※20131206※※※※※※", "※※※※※※※mBeemApplication.isConnected()="+mBeemApplication.isConnected()+";isConfig="+isConfig);
	    if (mBeemApplication.isConnected()) {
		startActivity(new Intent(this, ContactFrameActivity.class));//ContactListPullRefListActivity
		finish();
	    } else if ((isConfig==0)&&!ObjectCache.getStatus("isConnected", this)) {//!mBeemApplication.isAccountConfigured() && 
//	    	TerminalConfigMgr.setShowOfflineContacts(this,false);//默认显示离线用户
//	    	TerminalConfigMgr.setNotificationVibrate(this, true);//默认消息震动提示
//	    	TerminalConfigMgr.setUseAutoAway(this,true);//默认屏幕关闭修改状态
//	    	TerminalConfigMgr.setAutoAwayMsg(this, "离开");//默认屏幕关闭状态签名
		startActivity(new Intent(this, AccConfActivity.class));//AccountConfigure.class
		finish();
	    }
	}
	setContentView(R.layout.activity_login);//activity_login login
//	mTextView = (TextView) findViewById(R.id.log_as_msg);//R.id.log_as_msg
	SpiceApplication.getInstance().addActivity(this);
    }

    @Override
    protected void onStart() {
	super.onStart();
	
	/////////////////////////////20130605add start
	SharedPreferences sharedPrefs = this.getSharedPreferences(
            Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
	  Editor editor = sharedPrefs.edit();
	  editor.putInt(Constants.NOTIFICATION_ICON, R.drawable.sysmsg);//notification
	  editor.commit();
	/////////////////////////////20130605add end
	
	if (mSpiceApplication.isAccountConfigured() && !mIsResult //mBeemApplication.isAccountConfigured()
	    && BeemConnectivity.isConnected(getApplicationContext())
	    && (isConfig==1)) {
//	    mTextView.setText("");
		mTextViewStr = "";
	    Intent i = new Intent(this, LoginanimActivity.class);//进入登录界面
	    startActivityForResult(i, LOGIN_REQUEST_CODE);
	    mIsResult = false;
	}else if(ObjectCache.getStatus("isConnected", this)){
		if (mSpiceApplication.isAccountConfigured() && !mIsResult //mBeemApplication.isAccountConfigured()
			    && BeemConnectivity.isConnected(getApplicationContext())) {
//			    mTextView.setText("");
			    mTextViewStr = "";
			    Intent i = new Intent(this, LoginanimActivity.class);//进入登录界面
			    startActivityForResult(i, LOGIN_REQUEST_CODE);
			    mIsResult = false;
		}else if(!BeemConnectivity.isConnected(getApplicationContext())){
			startActivity(new Intent(this, ContactFrameActivity.class));//ContactListPullRefListActivity
			finish();
		}else{
//			mTextView.setText(R.string.login_start_msg);
			mTextViewStr = getString(R.string.login_start_msg);
			intent = new Intent(this, AccConfActivity.class);
			intent.putExtra("mTextViewStr", mTextViewStr);
			startActivity(intent);//AccountConfigure.class
			finish();
		}
	}else {
//	    mTextView.setText(R.string.login_start_msg);
	    mTextViewStr =  getString(R.string.login_start_msg);
		intent = new Intent(this, AccConfActivity.class);
		intent.putExtra("mTextViewStr", mTextViewStr);
		startActivity(intent);//AccountConfigure.class
		finish();
	}
    }
    
    @Override
    protected void onResume() {
		super.onResume();
		Intent intent = getIntent(); 
	    //0 false 1 true
		isConfig = intent.getIntExtra("isConfig", (int) 0); 
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	Log.d("######@@@@@@******Login requestCode resultCode******@@@@@@######", "resultCode="+resultCode+";requestCode="+requestCode);
	if (requestCode == LOGIN_REQUEST_CODE) {
	    mIsResult = true;
	    if (resultCode == Activity.RESULT_OK) {
			startActivity(new Intent(this, ContactFrameActivity.class));//ContactListPullRefListActivity
			finish();
	    } else if (resultCode == Activity.RESULT_CANCELED) {
			XmppConnectionAdapter.isPause = true;
			if(XmppConnectionAdapter.instance!=null){
			XmppConnectionAdapter.instance.resetApplication();
			try{
//				if(XmppConnectionAdapter.instance.getTimeReconnectExecutorService()!=null){
//					XmppConnectionAdapter.instance.shutdowntimeReconnectexecutorService();
//					XmppConnectionAdapter.instance.setTimeReconnectExecutorService(null);
//				}
//				if(XmppConnectionAdapter.instance.getExecutorService()!=null){
//					XmppConnectionAdapter.instance.shutdown();
//					XmppConnectionAdapter.instance.setExecutorService(null);
//				}
				XmppConnectionAdapter.instance.logoutReconnect();
			} catch (Exception e) {
				    e.printStackTrace();
			}
			}
			XmppConnectionAdapter.instance = null;
			if (data != null) {
			    String tmp = data.getExtras().getString("message");
//			    Toast.makeText(Login.this, tmp, Toast.LENGTH_SHORT).show();
	//		    mTextView.setText(tmp);
			    mTextViewStr = tmp;
			}
			intent = new Intent(this, AccConfActivity.class);
			intent.putExtra("mTextViewStr", mTextViewStr);
			startActivity(intent);//AccountConfigure.class
			finish();
	    }
	}
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//	super.onCreateOptionsMenu(menu);
//	MenuInflater inflater = getMenuInflater();
//	inflater.inflate(R.menu.login, menu);
//	return true;
//    }
//
//    @Override
//    public final boolean onOptionsItemSelected(MenuItem item) {
//	boolean result;
//	switch (item.getItemId()) {
//	    case R.id.login_menu_settings:
////		mTextView.setText("");
//	    	mTextViewStr = "";
//		startActivity(new Intent(Login.this, PreferenceActivity.class));//Settings
//		result = true;
//		break;
//	    case R.id.login_menu_about:
//		createAboutDialog();
//		result = true;
//		break;
//	    case R.id.login_menu_login:
//		if (mBeemApplication.isAccountConfigured()) {//如果本地存储了账户信息，则进入登录动画界面
//		    Intent i = new Intent(this, LoginanimActivity.class);
//		    startActivityForResult(i, LOGIN_REQUEST_CODE);
//		}
//		result = true;
//		break;
//	    default:
//		result = false;
//		break;
//	}
//	return result;
//    }

    /**
     * Create an about "BEEM" dialog.
     */
    private void createAboutDialog() {
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	String versionname;
	try {
	    PackageManager pm = getPackageManager();
	    PackageInfo pi = pm.getPackageInfo("com.stb.isharemessage", 0);
	    versionname = pi.versionName;
	} catch (PackageManager.NameNotFoundException e) {
	    versionname = "";
	}
	String title = getString(R.string.login_about_title, versionname);
	builder.setTitle(title).setMessage(R.string.login_about_msg).setCancelable(false);
	builder.setNeutralButton(R.string.login_about_button, new DialogInterface.OnClickListener() {

	    public void onClick(DialogInterface dialog, int whichButton) {
		dialog.cancel();
	    }
	});
	AlertDialog aboutDialog = builder.create();
	aboutDialog.show();
    }
}
